package per.chenxin.tools.foundation;

import java.io.FileNotFoundException;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class ConnectionWindow extends Dialog {

    protected Object result;

    protected Shell shell;

    protected Text textName;

    protected Text textClassName;

    protected Text textURI;

    protected Text textUser;

    protected Text textPassword;

    protected Button buttonAutoCommit;

    /**
     * Create the dialog
     *
     * @param parent
     * @param style
     */
    public ConnectionWindow(Shell parent, int style) {

        super(parent, style);
    }

    /**
     * Create the dialog
     *
     * @param parent
     */
    public ConnectionWindow(Shell parent) {

        this(parent, SWT.NONE);
    }

    /**
     * Open the dialog
     *
     * @return the result
     */
    public Object open() {

        result = null;
        createContents();
        shell.open();
        shell.layout();
        Display display = getParent().getDisplay();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
        return result;
    }

    /**
     * Create contents of the dialog
     */
    protected void createContents() {

        // shell = new Shell(getParent(), SWT.DIALOG_TRIM |
        // SWT.APPLICATION_MODAL);
        shell = new Shell(getParent());
        shell.setSize(500, 237);
        shell.setText("Connection Dialog");
        Point pointParentSize = getParent().getSize();
        Point pointParentLocation = getParent().getLocation();
        shell.setLocation(pointParentLocation.x + (pointParentSize.x - shell.getSize().x) / 2,
            pointParentLocation.y + (pointParentSize.y - shell.getSize().y) / 2);

        final Menu menu = new Menu(shell, SWT.BAR);
        shell.setMenuBar(menu);

        final MenuItem menuItemSave = new MenuItem(menu, SWT.NONE);
        menuItemSave.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(final SelectionEvent e) {

                MessageBox messageBox = new MessageBox(shell, SWT.YES | SWT.NO);
                messageBox.setMessage("save?");
                if (messageBox.open() == SWT.NO)
                    return;

                try {
                    Util.saveConnectionMap();
                } catch (FileNotFoundException e1) {
                    Util.showErrorMessage(shell, e1.getMessage());
                }
            }
        });
        menuItemSave.setText("&Save");

        final MenuItem menuItemDB = new MenuItem(menu, SWT.CASCADE);
        menuItemDB.setText("&DB");

        final Menu menu_1 = new Menu(menuItemDB);
        menuItemDB.setMenu(menu_1);

        final MenuItem menuItemOracle = new MenuItem(menu_1, SWT.NONE);
        menuItemOracle.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {

                textClassName.setText("oracle.jdbc.OracleDriver");
                textURI.setText("jdbc:oracle:thin:@localhost:1521:xe");

            }
        });
        menuItemOracle.setText("Oracle");

        MenuItem menuItemDB2 = new MenuItem(menu_1, SWT.NONE);
        menuItemDB2.setText("DB2");

        final List listConnection = new List(shell, SWT.MULTI | SWT.H_SCROLL | SWT.BORDER);
        listConnection.addMouseListener(new MouseAdapter() {

            public void mouseDoubleClick(final MouseEvent e) {

                String[] selectedItems = listConnection.getSelection();
                if (selectedItems.length != 1)
                    return;
                ConnectionItem connectionItem = (ConnectionItem) Util.getConnectionMap(false).get(
                    selectedItems[0]);
                loadConnectionItem(connectionItem);

            }
        });
        listConnection.setBounds(10, 8, 189, 127);
        loadConnection(listConnection);

        textClassName = new Text(shell, SWT.BORDER);
        textClassName.setBounds(235, 34, 180, 20);

        final Button button = new Button(shell, SWT.NONE);
        button.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(final SelectionEvent e) {

                if (textName.getText().trim().length() == 0)
                    return;
                if (Util.getConnectionMap(false).containsKey(textName.getText().trim())) {
                    MessageBox messageBox = new MessageBox(shell, SWT.YES | SWT.NO);
                    messageBox.setMessage("overwrite " + textName.getText().trim() + "?");
                    if (messageBox.open() == SWT.NO)
                        return;
                } else {
                    listConnection.add(textName.getText().trim());
                }

                ConnectionItem connectionItem = createConnectionItem();
                Util.getConnectionMap(false).put(connectionItem.getName(), connectionItem);

            }
        });
        button.setText("<-");
        button.setBounds(205, 59, 24, 22);

        final Label labelClassName = new Label(shell, SWT.NONE);
        labelClassName.setText("ClassName");
        labelClassName.setBounds(425, 32, 60, 20);

        textURI = new Text(shell, SWT.BORDER);
        textURI.setBounds(235, 61, 180, 20);

        final Label labelURI = new Label(shell, SWT.NONE);
        labelURI.setBounds(425, 59, 60, 20);
        labelURI.setText("URI");

        textUser = new Text(shell, SWT.BORDER);
        textUser.setBounds(235, 88, 180, 20);

        final Label labelUser = new Label(shell, SWT.NONE);
        labelUser.setBounds(425, 86, 60, 20);
        labelUser.setText("User");

        textPassword = new Text(shell, SWT.BORDER | SWT.PASSWORD);
        textPassword.setBounds(235, 115, 180, 20);

        final Label labelPassword = new Label(shell, SWT.NONE);
        labelPassword.setBounds(425, 113, 60, 20);
        labelPassword.setText("Password");

        textName = new Text(shell, SWT.BORDER);
        textName.setBounds(235, 8, 180, 20);

        final Label labelName = new Label(shell, SWT.NONE);
        labelName.setText("name");
        labelName.setBounds(425, 5, 60, 20);

        final Button buttonConnect = new Button(shell, SWT.NONE);
        buttonConnect.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(final SelectionEvent e) {

                result = createConnectionItem();
                shell.dispose();
            }
        });
        buttonConnect.setBounds(245, 141, 60, 22);
        buttonConnect.setText("&Connect");

        final Button buttonDelete = new Button(shell, SWT.NONE);
        buttonDelete.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(final SelectionEvent e) {

                String[] strsSelection = listConnection.getSelection();
                int[] intsSelectionIndice = listConnection.getSelectionIndices();
                if (strsSelection.length <= 0)
                    return;
                for (int i = 0; i < strsSelection.length; i++) {
                    Util.getConnectionMap(false).remove(strsSelection[i]);
                }
                listConnection.remove(intsSelectionIndice);

            }
        });
        buttonDelete.setBounds(70, 141, 60, 22);
        buttonDelete.setText("&Delete");

        buttonAutoCommit = new Button(shell, SWT.CHECK);
        buttonAutoCommit.setText("AutoCommit");
        buttonAutoCommit.setBounds(324, 144, 90, 20);
        //

    }

    private void loadConnection(List listConnection) {

        Map map = Util.getConnectionMap(false);
        Object[] objs = map.keySet().toArray();
        for (int i = 0; i < objs.length; i++) {
            listConnection.add((String) objs[i]);
        }
    }

    private void loadConnectionItem(ConnectionItem connectionItem) {

        textName.setText(Util.getNotNullString(connectionItem.getName()));
        textClassName.setText(Util.getNotNullString(connectionItem.getClassName()));
        textURI.setText(Util.getNotNullString(connectionItem.getURI()));
        textUser.setText(Util.getNotNullString(connectionItem.getUser()));
        textPassword.setText(Util.getNotNullString(connectionItem.getPassword()));
        buttonAutoCommit.setSelection(connectionItem.isAutoCommit());
    }

    private ConnectionItem createConnectionItem() {

        ConnectionItem connectionItem = new ConnectionItem();
        connectionItem.setName(textName.getText());
        connectionItem.setClassName(textClassName.getText());
        connectionItem.setURI(textURI.getText());
        connectionItem.setUser(textUser.getText());
        connectionItem.setPassword(textPassword.getText());
        connectionItem.setAutoCommit(buttonAutoCommit.getSelection());
        return connectionItem;
    }
}
